package io.github.wanggit.antrpc.console.configuration;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticsearchConfiguration {

    @Value("${antrpc.elasticsearch.hosts}")
    private String uris;

    @Value("${antrpc.elasticsearch.username}")
    private String userName;

    @Value("${antrpc.elasticsearch.password}")
    private String password;

    @Bean(name = "highLevelClient")
    public RestHighLevelClient highLevelClient() {
        RestClientBuilder restClientBuilder = RestClient.builder(makeHttpHost(uris));
        if (StringUtils.hasText(userName) && StringUtils.hasText(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            restClientBuilder.setHttpClientConfigCallback(
                    httpAsyncClientBuilder -> {
                        httpAsyncClientBuilder.disableAuthCaching();
                        return httpAsyncClientBuilder.setDefaultCredentialsProvider(
                                credentialsProvider);
                    });
        }
        return new RestHighLevelClient(restClientBuilder);
    }

    private HttpHost[] makeHttpHost(String uris) {
        if (null == uris) {
            throw new IllegalArgumentException();
        }
        String[] tmps = uris.split(",");
        HttpHost[] posts = new HttpHost[tmps.length];
        for (int i = 0; i < tmps.length; i++) {
            String uri = tmps[i].trim();
            String scheme = null;
            if (uri.startsWith("https://")) {
                scheme = "https";
                uri = uri.replaceFirst("http://", "");
            } else if (uri.startsWith("http://")) {
                scheme = "http";
                uri = uri.replaceFirst("http://", "");
            }
            String[] address = uri.split(":");
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            posts[i] = new HttpHost(ip, port, null == scheme ? "http" : scheme);
        }
        return posts;
    }
}
